package com.michaelbulava.TFS.tpignore;

import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.vfs.VirtualFile;
import com.michaelbulava.TFS.Messages;
import com.michaelbulava.TFS.log.FileLogger;
import com.microsoft.tfs.util.Check;
import com.microsoft.tfs.util.FileHelpers;
import com.microsoft.tfs.util.LocaleUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * Created by mbulava on 6/23/2015.
 */
final class TPIgnoreFileParser {
    private static final Logger log = FileLogger.getInstance(TPIgnoreFileParser.class);
    public static final char COMMENT_CHAR = '#';
    private static int compileFlags = -1000;

    private static synchronized int getCompileFlags(){
        if (compileFlags == -1000){
            if (FileHelpers.doesFileSystemIgnoreCase())
                compileFlags = 66;
            else
                compileFlags = 0;
        } else {
            compileFlags = 0;
        }
        return compileFlags;
    }

    public static Pattern[] load(VirtualFile ignoreFile){
        Check.notNull(ignoreFile, "file");
        if (!ignoreFile.exists())
            return null;

        List<Pattern> patterns = new ArrayList<Pattern>();

        BufferedReader reader = null;
        try{
            reader = new BufferedReader(new InputStreamReader(ignoreFile.getInputStream(),
                    ignoreFile.getCharset() != null ? ignoreFile.getCharset() : Charset.forName("UTF-8")));

            String line = null;

            int lineNumber = 0;
            while ((line = reader.readLine()) != null)
            {
                lineNumber++;
                line = line.trim();
                if ((line.length() != 0) && (!line.startsWith("#"))) {
                    try {

                        //patterns.add(Pattern.compile(line, getCompileFlags()));
                        patterns.add(Pattern.compile(Pattern.quote(line), getCompileFlags()));
                    } catch (PatternSyntaxException e) {
                        log.warn(MessageFormat.format(Messages.getString("TPIgnoreFileParser.CouldNotParseIgnorePatternFormat",
                                LocaleUtil.ROOT), new Object[]{line, ignoreFile.getPath(),
                                Integer.toString(lineNumber)}), e);

                        //TODO write to logger window too...
                    }
                }
            }
            return (Pattern[])patterns.toArray(new Pattern[patterns.size()]);
        } catch (IOException e) {
            log.error(MessageFormat.format("Error reading resource exclusion file {0}", new Object[]{ignoreFile}), e);
            return null;
        } finally {
            if (reader != null){
                try{
                    reader.close();
                } catch (IOException e){}
            }
        }
    }
}
